from typing import Tuple, Optional
import pyautogui
import pygetwindow as gw
from pywinauto import Application
from loguru import logger
import cv2
import numpy as np
from paddleocr import PaddleOCR
from config.settings import OCR_LANGUAGE, OCR_USE_GPU

class DesktopAutomation:
    def __init__(self):
        # 初始化OCR
        self.ocr = PaddleOCR(use_angle_cls=True, lang=OCR_LANGUAGE, use_gpu=OCR_USE_GPU)
        # 设置pyautogui安全设置
        pyautogui.FAILSAFE = True
        pyautogui.PAUSE = 0.5

    def find_window(self, title: str) -> Optional[gw.Window]:
        """查找窗口"""
        try:
            window = gw.getWindowsWithTitle(title)
            if window:
                logger.info(f"找到窗口: {title}")
                return window[0]
            logger.warning(f"未找到窗口: {title}")
            return None
        except Exception as e:
            logger.error(f"查找窗口失败: {str(e)}")
            raise

    def activate_window(self, window: gw.Window) -> None:
        """激活窗口"""
        try:
            window.activate()
            logger.info(f"窗口已激活: {window.title}")
        except Exception as e:
            logger.error(f"激活窗口失败: {str(e)}")
            raise

    def click_position(self, x: int, y: int) -> None:
        """点击指定坐标"""
        try:
            pyautogui.click(x, y)
            logger.info(f"点击坐标: ({x}, {y})")
        except Exception as e:
            logger.error(f"点击失败: {str(e)}")
            raise

    def type_text(self, text: str, interval: float = 0.1) -> None:
        """输入文本"""
        try:
            pyautogui.write(text, interval=interval)
            logger.info(f"输入文本: {text}")
        except Exception as e:
            logger.error(f"输入文本失败: {str(e)}")
            raise

    def find_image_on_screen(self, image_path: str, confidence: float = 0.9) -> Optional[Tuple[int, int]]:
        """在屏幕上查找图像"""
        try:
            location = pyautogui.locateCenterOnScreen(image_path, confidence=confidence)
            if location:
                logger.info(f"找到图像: {image_path} at {location}")
                return location
            logger.warning(f"未找到图像: {image_path}")
            return None
        except Exception as e:
            logger.error(f"查找图像失败: {str(e)}")
            raise

    def ocr_screen_region(self, region: Optional[Tuple[int, int, int, int]] = None) -> list:
        """对屏幕区域进行OCR识别"""
        try:
            # 截取屏幕区域
            screenshot = pyautogui.screenshot(region=region)
            # 转换为OpenCV格式
            img_cv = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
            # OCR识别
            result = self.ocr.ocr(img_cv)
            logger.info(f"OCR识别完成，找到 {len(result)} 个文本区域")
            return result
        except Exception as e:
            logger.error(f"OCR识别失败: {str(e)}")
            raise

    def connect_to_window_app(self, window_title: str) -> Application:
        """连接到Windows应用程序"""
        try:
            app = Application().connect(title=window_title)
            logger.info(f"成功连接到应用程序: {window_title}")
            return app
        except Exception as e:
            logger.error(f"连接应用程序失败: {str(e)}")
            raise

    def press_key_combination(self, *keys: str) -> None:
        """按下组合键"""
        try:
            pyautogui.hotkey(*keys)
            logger.info(f"按下组合键: {' + '.join(keys)}")
        except Exception as e:
            logger.error(f"按下组合键失败: {str(e)}")
            raise

    def drag_mouse(self, start_x: int, start_y: int, end_x: int, end_y: int, duration: float = 0.5) -> None:
        """拖拽鼠标"""
        try:
            pyautogui.moveTo(start_x, start_y)
            pyautogui.dragTo(end_x, end_y, duration=duration)
            logger.info(f"拖拽完成: ({start_x}, {start_y}) -> ({end_x}, {end_y})")
        except Exception as e:
            logger.error(f"拖拽失败: {str(e)}")
            raise 